<template>

  <div class="flight-query-panel">


    <div class="panel-content" v-if="activeTab === 'flight'">
      <div class="query-section">
        <!-- 飞行轨迹筛选 -->
        <div class="section-title flight-path-title">
          <div class="section-label">飞行轨迹：</div>
          <div class="checkbox-group">
            <el-checkbox-group v-model="queryParams.sources" @change="realTimeFlightsData"
              class="custom-checkbox-group">
              <el-checkbox v-for="item in aircraftType" :key="item" :label="item.label" :value="item.value"
                class="custom-checkbox"></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 飞机编号筛选 -->
        <div class="section-title aircraft-code-title">
          <div class="section-label">飞机编号：</div>
          <div class="filter-action">
            <div class="selected-codes" @click="openCodeSelector">
              <span v-if="selectedCodes.length === 0">全部</span>
              <span v-else>{{ selectedCodesText }}</span>
              <el-icon class="filter-icon">
                <Filter />
              </el-icon>
            </div>

          </div>
        </div>

        <!-- 架次列表标题 -->
        <div class="section-title flight-list-title">
          <div class="section-label">架次列表：</div>
        </div>
      </div>

      <!-- 架次列表内容 -->
      <div class="flight-list-container">
        <div v-if="flightList.length > 0" class="flights-wrapper">
          <div v-for="(flight, index) in flightList" :key="index" class="flight-item"
            :class="{ selected: selectedFlights.includes(flight.order), located: locatedFlight === flight.order }"
            @click="toggleFlightSelection(flight.order)">
            <div class="flight-info">
              <div class="flight-name">{{ flight.order }}</div>
              <div class="flight-meta">
                <span class="flight-time">{{ flight.startsAt }}</span>
                <span class="flight-code">{{ flight.airplane }}</span>
              </div>
            </div>
            <div class="flight-actions">
              <el-tooltip content="架次详情" placement="top" :show-after="300">
                <el-button size="small" type="primary" circle @click.stop="openDmtDrawer(flight)">
                  <el-icon>
                    <WarningFilled />
                  </el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="定位飞机" placement="top" :show-after="300">
                <el-button size="small" type="success" circle :class="{ 'located-btn': locatedFlight === flight.order }"
                  @click.stop="locateFlight(flight.order)">
                  <el-icon>
                    <LocationInformation />
                  </el-icon>
                </el-button>
              </el-tooltip>

            </div>
          </div>
        </div>

        <!-- 架次列表空状态 -->
        <div v-else class="empty-state">
          <img src="@/assets/images/empty-data.png" alt="暂无数据" class="empty-icon" />
          <p class="mt10px">暂无架次</p>
        </div>
      </div>
    </div>
    <!-- 飞机编号选择器弹窗 -->
    <el-dialog title="飞机编号选择" v-model="codeDialogVisible" width="500px" :modal="true" :append-to-body="true"
      :close-on-click-modal="false" destroy-on-close class="code-selector-dialog">
      <div class="code-selector">
        <div class="code-manage">
          <el-checkbox v-model="selectAllCodes" label="全选" class="code-checkbox">
          </el-checkbox>
          <el-input v-model="codeSearchText" placeholder="搜索编号" class="code-search" prefix-icon="Search"
            clearable></el-input>
        </div>

        <div class="code-list">
          <el-checkbox-group v-model="queryParams.airplanes" class="code-checkbox-group">
            <div v-for="(code, index) in filteredAircraftCodes" :key="index" class="code-item">
              <el-checkbox :label="code.label" :value="code.value" class="code-checkbox">
              </el-checkbox>
            </div>
          </el-checkbox-group>

          <!-- 空状态 -->
          <div v-if="filteredAircraftCodes.length === 0" class="empty-search">
            <el-icon>
              <Search />
            </el-icon>
            <p>未找到匹配的编号</p>
          </div>
        </div>

        <div class="selection-summary">
          已选择 <span>{{ queryParams.airplanes.length }}</span> /
          {{ aircraftCodes.length }} 个编号
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCodeSelection">取消</el-button>
          <el-button type="primary" @click="confirmCodeSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, inject } from "vue";
import {
  filterAddOrModify,
  removeMarker,
  clearAllMarkersAndTrails,
  getMap
} from "@/mapbox/main/index.js";
import {
  ArrowRight,
  View,
  Edit,
  Delete,
  Plus,
  Filter,
  Search,
  Aim,
  LocationInformation
} from "@element-plus/icons-vue";
import { getDictList, realTimeFlights } from "@/api/aircraft";
import { ElMessage, dayjs } from "element-plus";
import drawerStore from "@/stores/modules/drawer";

import useInfoDataStore from "@/stores/modules/infoData";


const infoData = useInfoDataStore();

const drawer = drawerStore();

// 定义事件
const emit = defineEmits(['select-flight', 'show-drawer', 'loading-change']);

// 当前激活的标签页
const activeTab = ref("flight");

// 查询参数
const queryParams = ref({
  sources: [],
  airplanes: [],
});

// 飞机编号数据
const aircraftCodes = ref([]);
// 飞机轨迹类型
const aircraftType = ref([]);

// 选中的编号
const selectedCodes = ref([]);
const tempSelectedCodes = ref([]);
const codeSearchText = ref("");

// 编号选择器弹窗
const codeDialogVisible = ref(false);

// 存储每个架次的EventSource
const eventSources = ref({});

// 飞行轨迹颜色映射
const trailColors = [
  "#FF0000", // 红色
  "#00AA00", // 绿色
  "#0000FF", // 蓝色
  "#FF9900", // 橙色
  "#9900FF", // 紫色
  "#00CCFF", // 青色
  "#FF00FF", // 粉色
  "#FFFF00"  // 黄色
];

// DMT探测抽屉相关
const dmtDrawerVisible = ref(false);
const currentDmtFlight = ref(null);
const dmtData = ref({
  temperature: null,
  humidity: null,
  airPressure: null,
  windSpeed: null,
  windDirection: null,
  typesAndDosagesOfCatalysts: null,
  currentNumberOfFlares: null,
  numberOfLeftFlameBullets: null,
  numberOfRightFlameBullets: null,
  flameState: null
});



// 定位飞机相关
const locatedFlight = ref(null);



// 获取字典数据
const getDictListData = async () => {
  try {
    const res = await getDictList();
    aircraftCodes.value = res.find((item) => item.type === "AIRPLANE").elements;
    aircraftType.value = res.find((item) => item.type === "SOURCE").elements;
    queryParams.value.sources = aircraftType.value.map((item) => item.value);
    queryParams.value.airplanes = aircraftCodes.value.map((item) => item.value);
    infoData.dictionaries = res
    realTimeFlightsData();
  } catch (error) {
    console.error(error);
  }
};

// 获取实时架次数据
const realTimeFlightsData = async () => {
  try {
    const res = await realTimeFlights(queryParams.value);
    flightList.value = res;
  } catch (error) {
    console.error(error);
  }
};

// 关闭指定架次的EventSource
const closeEventSource = (id) => {
  if (eventSources.value[id]) {
    eventSources.value[id].close();
    delete eventSources.value[id];

    // 从地图上移除轨迹和标记
    const map = getMap();
    if (map) {
      try {
        filterAddOrModify(map, {
          id: id,
          positions: [0, 0], // 移到地图外的位置
          info: {
            visible: false // 设置为不可见
          }
        });
        console.log(`已从地图上移除架次 ${id} 的标记`);
      } catch (error) {
        console.error(`移除架次 ${id} 标记失败:`, error);
      }
    }
  }
};

// 关闭所有EventSource
const closeAllEventSources = () => {
  Object.keys(eventSources.value).forEach(id => {
    eventSources.value[id].close();
  });
  eventSources.value = {};
  clearAllMarkersAndTrails(getMap())
};

// 解析飞行数据
const parseData = (dataString) => {
  const fields = [
    'flightNumber', 'dataSource', 'timeStamp', 'longitude', 'latitude', 'altitude', 'groundSpeed', 'course',
    'temperature', 'humidity', 'airPressure', 'windSpeed', 'windDirection', 'typesAndDosagesOfCatalysts', 'currentNumberOfFlares',
    'numberOfLeftFlameBullets', 'numberOfRightFlameBullets', 'flameState', 'trueAirspeed', 'model'
  ];

  const values = dataString.split(',');
  const dataObject = {};

  for (let i = 0; i < fields.length; i++) {
    dataObject[fields[i]] = values[i] !== 'null' ? values[i] : null;
  }

  return dataObject;
};

// 处理DMT数据，转换为适合图表的格式
const formatDmtData = (data) => {
  const formatted = {};

  if (!data || Object.keys(data).length === 0) {
    console.warn('DMT数据为空');
    return {
      temperature: 0,
      humidity: 0,
      airPressure: 0,
      windSpeed: 0,
      windDirection: 0,
      currentNumberOfFlares: 0,
      numberOfLeftFlameBullets: 0,
      numberOfRightFlameBullets: 0,
      flameState: '0'
    };
  }

  for (const key in data) {
    if (data[key] === null || data[key] === undefined || data[key] === 'null') {
      formatted[key] = 0;
    } else if (['temperature', 'humidity', 'airPressure', 'windSpeed', 'windDirection', 'currentNumberOfFlares',
      'numberOfLeftFlameBullets', 'numberOfRightFlameBullets'].includes(key)) {
      formatted[key] = parseFloat(data[key]) || 0;
    } else {
      formatted[key] = data[key];
    }
  }

  return formatted;
};

const isTrajectoryLoading = ref(false);
// 获取轨迹数据
const getWithTrajectory = async (id) => {
  try {
    const colorIndex = selectedFlights.value.indexOf(id) % trailColors.length;
    const trailColor = trailColors[colorIndex];

    // 设置加载状态
    isTrajectoryLoading.value = true;
    emit('loading-change', true);
    // 设置加载超时处理
    const loadingTimeout = setTimeout(() => {
      if (isTrajectoryLoading.value) {
        isTrajectoryLoading.value = false;
        emit('loading-change', false);
        ElMessage.warning("轨迹数据加载超时，请稍后再试");
      }
    }, 15000); // 15秒超时

    eventSources.value[id] = new EventSource(
      `${import.meta.env.VITE_WEB_BASE_API}/track/realtime/sse?fn=${id}`
    );

    eventSources.value[id].onmessage = (event) => {
      try {
        // 清除超时定时器
        clearTimeout(loadingTimeout);

        const dataArray = JSON.parse(event.data);

        const allDataPoints = dataArray.map(item => parseData(item));
        const parsedData = allDataPoints[allDataPoints.length - 1];

        eventSources.value[id]._latestData = event.data;
        eventSources.value[id]._parsedDataPoints = allDataPoints;

        if (dataArray.length > 1) {
          // console.log(`收到${dataArray.length}条历史数据`);
        } else {
          // console.log(`收到实时数据更新`);

          if (eventSources.value[id]._allHistoryData) {
            eventSources.value[id]._allHistoryData.push(parsedData);
          }
        }

        if (!eventSources.value[id]._allHistoryData) {
          eventSources.value[id]._allHistoryData = [...allDataPoints];
        } else if (dataArray.length === 1) {
          eventSources.value[id]._allHistoryData.push(parsedData);
        }

        if (currentDmtFlight.value && currentDmtFlight.value.order === id) {
          dmtData.value = {
            temperature: parsedData.temperature,
            humidity: parsedData.humidity,
            airPressure: parsedData.airPressure,
            windSpeed: parsedData.windSpeed,
            windDirection: parsedData.windDirection,
            typesAndDosagesOfCatalysts: parsedData.typesAndDosagesOfCatalysts,
            currentNumberOfFlares: parsedData.currentNumberOfFlares,
            numberOfLeftFlameBullets: parsedData.numberOfLeftFlameBullets,
            numberOfRightFlameBullets: parsedData.numberOfRightFlameBullets,
            flameState: parsedData.flameState,
            longitude: parsedData.longitude,
            latitude: parsedData.latitude,
            altitude: parsedData.altitude,
            course: parsedData.course,
            groundSpeed: parsedData.groundSpeed
          };

          if (drawer.showDrawer) {
            const formattedData = formatDmtData({ ...dmtData.value });

            const payload = {
              id: currentDmtFlight.value.order,
              takeoffTime: currentDmtFlight.value.startsAt,
              airplane: currentDmtFlight.value.airplane,
              rawDmtData: formattedData,
              timestamp: parsedData.timeStamp,
              longitude: parsedData.longitude,
              latitude: parsedData.latitude,
              altitude: parsedData.altitude,
              temperature: formattedData.temperature,
              humidity: formattedData.humidity,
              airPressure: formattedData.airPressure,
              windSpeed: formattedData.windSpeed,
              windDirection: formattedData.windDirection,
              speed: parsedData.groundSpeed,
              direction: parsedData.course
            };
            infoData.historyDataList.push(payload);
            emit('show-drawer');
          }
        }
        // parsedData.id = id;

        if (isTrajectoryLoading.value) {
          isTrajectoryLoading.value = false;
          emit('loading-change', false);
        }

        filterAddOrModify(getMap(), {
          id: id,
          positions: [Number(parsedData.longitude), Number(parsedData.latitude)],
          info: {
            ...parsedData,
            color: trailColor,
            width: 2,
            showLabel: true
          }
        });

        if (dataArray.length > 1) {
          const historyPositions = allDataPoints.map(data => {
            return [Number(data.longitude), Number(data.latitude)];
          });


        }

        const completeTrackData = eventSources.value[id]._allHistoryData || allDataPoints;
        if (completeTrackData && completeTrackData.length > 0) {
          const completePositions = completeTrackData.map(data => {
            return [Number(data.longitude), Number(data.latitude)];
          });


          if (dataArray.length === 1) {
            // console.log(`为架次${id}更新轨迹，当前共有${completePositions.length}个轨迹点`);
          }
        }
      } catch (error) {
        clearTimeout(loadingTimeout);
        isTrajectoryLoading.value = false;
        emit('loading-change', false);
        console.error("解析轨迹数据失败:", error);
      }
    };


    eventSources.value[id].onerror = () => {
      clearTimeout(loadingTimeout);
      isTrajectoryLoading.value = false;
      emit('loading-change', false);
      ElMessage.error("轨迹数据连接失败");

      // 从选中列表中移除
      const index = selectedFlights.value.indexOf(id);
      if (index > -1) {
        selectedFlights.value.splice(index, 1);
      }

      // 关闭连接并清理资源
      closeEventSource(id);
    };
  } catch (error) {
    isTrajectoryLoading.value = false;
    emit('loading-change', false);
    console.error("获取轨迹数据失败:", error);
    ElMessage.error("获取轨迹数据失败");
  }
};

onMounted(() => {
  getDictListData();
});

onBeforeUnmount(() => {
  closeAllEventSources();

});

// 筛选后的编号列表
const filteredAircraftCodes = computed(() => {
  if (!codeSearchText.value) return aircraftCodes.value;
  return aircraftCodes.value.filter(
    (item) =>
      item.label.toLowerCase().includes(codeSearchText.value.toLowerCase()) ||
      (item.remark &&
        item.remark.toLowerCase().includes(codeSearchText.value.toLowerCase()))
  );
});

// 选中的编号文本（逗号分隔）
const selectedCodesText = computed(() => {
  if (selectedCodes.value.length === 0) return "全部";
  if (selectedCodes.value.length === aircraftCodes.value.length) return "全部";
  const selectedLabels = selectedCodes.value.map((value) => {
    const foundItem = aircraftCodes.value.find((item) => item.value === value);
    return foundItem ? foundItem.label : value;
  });

  return selectedLabels.join("，");
});

// 实况架次
const flightList = ref([]);
// 选中的航班
const selectedFlights = ref([]);

const selectAllCodes = computed({
  get() {
    return queryParams.value.airplanes.length === aircraftCodes.value.length;
  },
  set(val) {
    if (val) {
      queryParams.value.airplanes = aircraftCodes.value.map(
        (item) => item.value
      );
    } else {
      queryParams.value.airplanes = [];
    }
  },
});

// 打开编号选择器
const openCodeSelector = () => {
  tempSelectedCodes.value = [...selectedCodes.value];
  queryParams.value.airplanes = [...selectedCodes.value];

  if (
    selectedCodes.value.length === 0 ||
    selectedCodes.value.length === aircraftCodes.value.length
  ) {
    queryParams.value.airplanes = aircraftCodes.value.map((item) => item.value);
  }

  codeSearchText.value = "";
  codeDialogVisible.value = true;
};

// 取消编号选择
const cancelCodeSelection = () => {
  selectedCodes.value = [...tempSelectedCodes.value];
  codeDialogVisible.value = false;
};

// 确认编号选择
const confirmCodeSelection = () => {
  selectedCodes.value = [...queryParams.value.airplanes];

  if (
    selectedCodes.value.length === 0 ||
    selectedCodes.value.length === aircraftCodes.value.length
  ) {
    selectedCodes.value = [];
  }

  codeDialogVisible.value = false;
  realTimeFlightsData();
};


// 打开DMT探测抽屉
const openDmtDrawer = (flight) => {
  // 检查架次是否已被选中
  if (!Array.isArray(selectedFlights.value) || !selectedFlights.value.includes(flight.order)) {
    ElMessage.warning('请先选择该架次，才能查看DMT数据');
    return;
  }

  // 设置当前DMT飞行对象
  currentDmtFlight.value = flight;
  drawer.toggleDrawer();
};

// 关闭DMT抽屉
const closeDrawer = () => {
  drawer.toggleDrawer();

  currentDmtFlight.value = null;
};

// 监听DMT抽屉关闭事件
watch(dmtDrawerVisible, (val) => {
  if (!val) {
    closeDrawer();
  }
});

// 定义导出方法，供父组件调用
defineExpose({
  closeDrawer,
  closeAllEventSources,
  selectedFlights
});

// 定位到飞机
const locateFlight = (flightId) => {
  locatedFlight.value = locatedFlight.value === flightId ? null : flightId;

  if (locatedFlight.value) {
    const flight = flightList.value.find(item => item.order === flightId);
    if (flight) {
      emit('select-flight', {
        flightNo: flight.order,
        date: new Date().toISOString().split('T')[0],
        takeoffTime: flight.startsAt,
        airplane: flight.airplane
      });

      const map = getMap();
      if (map) {
        console.log('定位到航班:', flight);
      }
    }
  }
};

// 切换架次选择
const toggleFlightSelection = (id) => {
  const index = selectedFlights.value.indexOf(id);

  if (index > -1) {
    // 如果已选中，则移除
    closeEventSource(id);
    removeMarker(getMap(), id);
    selectedFlights.value.splice(index, 1);

    if (locatedFlight.value === id) {
      locatedFlight.value = null;
    }

    // 通知父组件清除该架次
    emit("select-flight", null);
  } else {

    // if (selectedFlights.value.length > 0) {
    //   // 清除所有已选中的架次
    //   const previousSelectedFlights = [...selectedFlights.value];
    //   previousSelectedFlights.forEach(flightId => {
    //     closeEventSource(flightId);
    //   });
    //   selectedFlights.value = [];
    // }

    // 添加新选中的架次
    selectedFlights.value.push(id);
    getWithTrajectory(id);
  }
};
</script>

<style lang="scss" scoped>
.flight-query-panel {
  width: 100%;
  max-height: 89vh;

  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: auto;

  .panel-content {
    flex: 1;
    padding: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .query-section {
      flex-shrink: 0;
      padding-right: 5px;

      .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        padding-bottom: 8px;
        font-size: 14px;
        color: #303133;
        border-bottom: 1px solid #ebeef5;

        .section-label {
          min-width: 70px;
          font-weight: 500;
        }

        .checkbox-group {
          flex: 1;
          overflow: auto;

          .custom-checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;

            .custom-checkbox {
              margin-right: 0 !important;
              border-radius: 4px;
              padding: 2px;
              box-sizing: border-box;

              :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
                color: #409eff;
              }

              :deep(.el-checkbox__label) {
                font-size: 12px;
                padding-left: 6px;
              }

              :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
                background-color: #409eff;
                border-color: #409eff;
              }
            }
          }
        }

        &.flight-path-title {
          margin-bottom: 10px;
        }

        &.aircraft-code-title {
          margin-bottom: 10px;

          .filter-action {
            flex: 1;

            .selected-codes {
              display: inline-flex;
              align-items: center;
              color: #409eff;
              cursor: pointer;
              font-size: 13px;
              background-color: #f0f7ff;
              padding: 4px 10px;
              border-radius: 4px;
              max-width: 200px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              transition: all 0.2s;
              border: 1px solid #e0efff;

              &:hover {
                background-color: #e0efff;
                border-color: #c6e2ff;
              }

              .filter-icon {
                margin-left: 6px;
                font-size: 12px;
              }
            }

            .selection-counts {
              margin-top: 4px;
              margin-left: 2px;
              font-size: 12px;
              color: #606266;

              span {
                color: #409eff;
                font-weight: 500;
              }
            }
          }
        }

        &.flight-list-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-bottom: none;
          margin-bottom: 6px;
          padding-bottom: 0;

          .add-flight-btn {
            font-size: 12px;
            padding: 4px 8px;
            height: 28px;

            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }

    .flight-list-container {
      flex: 1;
      max-height: 75vh;

      overflow-y: auto;
      margin-top: 0;
      padding: 5px;
      background-color: #fff;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #d0d7de;
        border-radius: 10px;
      }

      &::-webkit-scrollbar-track {
        background-color: transparent;
      }

      .flights-wrapper {
        height: 100%;
      }

      .flight-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 10px;
        border-radius: 4px;
        border: 1px solid #edf2fc;
        margin-bottom: 6px;
        cursor: pointer;
        transition: all 0.2s;
        background-color: #fff;

        &:hover {
          background-color: #f5f9ff;
          border-color: #d9e8ff;
        }

        &.selected {
          background-color: #ecf5ff;
          border-color: #b3d8ff;
        }

        &.located {
          background-color: #f0f9eb;
          border-color: #c2e7b0;
          box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
        }

        .flight-info {
          .flight-name {
            font-weight: 500;
            font-size: 14px;
            margin-bottom: 4px;
            color: #303133;
          }

          .flight-meta {
            font-size: 12px;
            color: #909399;
            display: flex;
            gap: 8px;

            .flight-time {
              color: #606266;
            }

            .flight-code {
              color: #67c23a;
              font-weight: 500;
            }
          }
        }

        .flight-actions {
          display: flex;
          gap: 6px;

          .el-button {
            padding: 6px;
            font-size: 12px;
            transition: all 0.3s;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            }

            &.located-btn {
              background-color: #67c23a;
              border-color: #67c23a;
              color: white;
              animation: pulse 1.5s infinite;
            }
          }
        }
      }

      // 空状态样式
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 20px 0;
        box-sizing: border-box;

        .empty-icon {
          width: 130px;
          opacity: 0.7;
        }

        p {
          color: #909399;
          font-size: 13px;
          margin-bottom: 12px;
        }

        .el-button {
          padding: 6px 12px;
          font-size: 12px;
        }
      }
    }
  }
}

// 编号选择器样式
.code-selector-dialog {
  :deep(.el-dialog__header) {
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 15px;
  }

  :deep(.el-dialog__footer) {
    padding: 10px 15px;
    border-top: 1px solid #ebeef5;
  }
}

.code-selector {
  .code-manage {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .code-search {
      width: 180px;
    }
  }

  .code-list {
    height: 300px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 10px;

    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 10px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }

    .code-checkbox-group {
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 5px 0;

      .code-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 10px;
        transition: all 0.2s;
        border-bottom: 1px solid #f5f7fa;

        &:hover {
          background-color: #f7f9fc;
        }

        &:last-child {
          border-bottom: none;
        }

        .code-checkbox {
          width: 100%;
          font-size: 13px;
          display: flex;
          align-items: center;

          :deep(.el-checkbox__label) {
            display: flex;
            justify-content: space-between;
            width: 100%;
            padding-left: 8px;
          }

          .code-value {
            font-weight: 500;
            color: #303133;
          }

          .code-remark {
            color: #909399;
            font-size: 12px;
            margin-left: 8px;
          }
        }
      }
    }

    // 搜索为空状态
    .empty-search {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      color: #909399;

      .el-icon {
        font-size: 24px;
        margin-bottom: 8px;
        opacity: 0.5;
      }

      p {
        font-size: 13px;
      }
    }
  }

  .selection-summary {
    text-align: right;
    font-size: 12px;
    color: #606266;
    margin-bottom: 0;

    span {
      color: #409eff;
      font-weight: 500;
    }
  }
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-spinner {
  display: flex;
  gap: 8px;

  &::before,
  &::after,
  & span {
    content: '';
    width: 8px;
    height: 8px;
    display: block;
    background-color: #409EFF;
    border-radius: 50%;
    animation: bounce 0.5s ease-in-out infinite;
  }

  &::before {
    animation-delay: -0.3s;
  }

  & span {
    animation-delay: -0.15s;
  }
}

.loading-text {
  color: #409EFF;
  font-size: 14px;
  font-weight: normal;
}

@keyframes bounce {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}
</style>